# 在这里写上你的代码 :-)
# 模拟金币下落的效果，用户可以控制左右键来接住金币

from microbit import *
import random

# 定义二维数组
matrix = [[0 for i in range(5)] for j in range(5)]
# 金币的位置, y坐标位置随机产生
yCoin = random.randint(0, 4)
xCoin = 0
matrix[xCoin][yCoin] = 5
# 玩家位置, 起始位置在第四行中间
xPlay = 4
yPlay = 2
# 玩家得分
score = 0
# 游戏时间
time = 0

# 定义图案的字符串函数
def getImageString():
    s = ""
    for row in range(5):
        for col in range(5):
            s += str(matrix[row][col])
        s += ":"
    return s


# 重新开始坠落金币
def resetCoin():
    global yCoin, xCoin
    matrix[xCoin][yCoin] = 0
    yCoin = random.randint(0, 4)
    xCoin = 0
    matrix[xCoin][yCoin] = 5


while True:
    # 是不是接到了金币？
    if xPlay == xCoin and yPlay == yCoin:
        score += 1
        resetCoin()
        pin1.write_digital(1)
        sleep(1000)
        pin1.write_digital(0)
    matrix[xPlay][yPlay] = 0
    # 此处不能使用 is_pressed 方法，因为会连续出发动作，was_pressed 和 get_presses 则会被调用后自动复位，避免连续触发
    if button_a.was_pressed() and yPlay > 0:
        yPlay -= 1
    elif button_b.was_pressed() and yPlay < 4:
        yPlay += 1
    matrix[xPlay][yPlay] = 9
    display.show(Image(getImageString()))

    sleep(100)
    time += 100
    # 金币每隔固定时间下落一格
    if time % 500 == 0:
        matrix[xCoin][yCoin] = 0
        if xCoin >= 4:
            resetCoin()
        else:
            xCoin += 1
            matrix[xCoin][yCoin] = 5
